package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.utils.DateUtils;
import com.cykj.common.utils.StringUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.BizPosMessage;
import com.cykj.pos.domain.dto.ProfitDeatailDTO;
import com.cykj.pos.mapper.BizMerchantInfoMapper;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.mapper.BizTransactionAmountMapper;
import com.cykj.pos.service.*;
import com.cykj.pos.util.BigDecimalUtil;
import com.cykj.pos.util.DESHelperUtil;
import com.cykj.system.domain.Wallet;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.commons.math3.util.FastMath.floor;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/noauth/posv1")
@Api(tags = "交易通知")
public class PosV1TransactioNotice {

    private final IBizTransactionAmount bizTransactionAmount;

    private final IBizMerchTransactionsService bizMerchTransactionsService;

    private final TransactionService transactionService;

    private final IBizPosMachineStatusRecordsService recordsService;

    private final IBizMerchantService bizMerchantService;

    private final IBizPosMachineService bizPosMachineService;

    private final IBizMerchantEntryService bizMerchantEntryService;

    private final IBizTrackRecordService bizTrackRecordService;

    private final IBizWalletService bizWalletService;

    private final BizMerchantMapper bizMerchantMapper;

    private final IBizUserAccountService bizUserAccountService;

    private final IBizMerchBillService merchBillService;

    private final IBizSubAccountService bizSubAccountService;

    private final BizTransactionAmountMapper bizTransactionAmountMapper;

    private final BizMerchantInfoMapper bizMerchantInfoMapper;



    @ApiOperation("交易通知")
    @PostMapping("/trading")
    public Map transact(@RequestBody SynchronizationDataDTO sy) {
        System.out.println("------------------------------------------------------------------");
        System.out.println("------------------------------------------------------------------");
        System.out.println("--------pos1.0交易通知：" + sy + "---------");
        System.out.println("------------------------------------------------------------------");
        System.out.println("------------------------------------------------------------------");
        Map<String, String> map = new HashMap<>();
        BizPosMachine posMachineBySnCode = bizPosMachineService.getPosMachineBySnCode(sy.getPos_sn());
        //转换时间格式
        String year = sy.getHost_date().substring(0, 4);
        String month = sy.getHost_date().substring(4, 6);
        String day = sy.getHost_date().substring(6, 8);
        String hour = sy.getHost_time().substring(0, 2);
        String minute = sy.getHost_time().substring(2, 4);
        String second = sy.getHost_time().substring(4, 6);
        String date = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        sy.setHost_date(date);
        String snCode = sy.getPos_sn();// 设备号
        //判断这笔交易是不是已经存进去了
        Integer transaction = bizMerchTransactionsService.findTransaction(sy.getPos_sn(), String.valueOf(sy.getAmnount()), String.valueOf(sy.getHost_date()),String.valueOf(sy.getTrans_type()));

        //整理费率单笔附加费
        if(StringUtils.isNotBlank(sy.getTextra_amt())){
            BigDecimal amt=new BigDecimal(sy.getTextra_amt());
            sy.setFee_name(sy.getFee_name()+"+"+amt.divide(new BigDecimal("100"),2,BigDecimal.ROUND_DOWN));
        }

        if (transaction > 0) {
            if("sims".equals(sy.getNotice_type())&&"1".equals(sy.getTran_sim())){
                String uuid= IdWorker.getIdStr();
                sy.setUuid(uuid);
                boolean isOrNo=bizTransactionAmount.isOrNo(sy);
                if(!isOrNo){
                    map.put("ret_code", "0");
                    map.put("ret_msg", "已有该笔交易");
                    System.out.println("----------");
                    System.out.println("----交易已存在------");
                    System.out.println("----------");
                    return map;
                }
                sy.setAmnount((double) sy.getSim_amt());
                //流量费
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sy.setSim_amt((int) floor(sy.getAmnount()));
                //创建流量费费用收据列表
                BizFeesCharged bizFeesCharged=bizTransactionAmount.createSimAmt(sy);
                SynchronizationDataDTO sy1 = new SynchronizationDataDTO();
                sy1.setSim_amt((int) floor(sy.getAmnount()));
                sy1.setPos_sn(sy.getPos_sn());
                sy1.setHost_date(sdf.format(new Date()));
                sy1.setUuid(bizFeesCharged.getUuid());
                bizTransactionAmount.returnSimAmt(sy1,false);
                int i = recordsService.disposeOneVersionRecords(snCode);
                Map<String, String> map1 = new HashMap<>();
                if (i == 1) {
                    System.out.println("------------");
                    System.out.println("------------");
                    System.out.println("------设备没有报件------" + snCode);
                    System.out.println("------------");
                    map1.put("ret_code", "0");
                    map1.put("ret_msge", "该设备没有报件" + snCode);
                    return map1;
                }
            }
            map.put("ret_code", "0");
            map.put("ret_msg", "已有该笔交易");
            System.out.println("----------");
            System.out.println("----交易已存在------");
            System.out.println("----------");
            return map;
        }

        if("sims".equals(sy.getNotice_type())&&"1".equals(sy.getTran_sim())){
            String uuid= IdWorker.getIdStr();
            sy.setUuid(uuid);
            boolean isOrNo=bizTransactionAmount.isOrNo(sy);
            if(!isOrNo){
                map.put("ret_code", "0");
                map.put("ret_msg", "已有该笔交易");
                System.out.println("----------");
                System.out.println("----交易已存在------");
                System.out.println("----------");
                return map;
            }
            sy.setAmnount((double) sy.getSim_amt());
            //流量费
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sy.setSim_amt((int) floor(sy.getAmnount()));
            //创建流量费费用收据列表
            BizFeesCharged bizFeesCharged=bizTransactionAmount.createSimAmt(sy);
            SynchronizationDataDTO sy1 = new SynchronizationDataDTO();
            sy1.setSim_amt((int) floor(sy.getAmnount()));
            sy1.setPos_sn(sy.getPos_sn());
            sy1.setHost_date(sdf.format(new Date()));
            sy1.setUuid(bizFeesCharged.getUuid());
            bizTransactionAmount.returnSimAmt(sy1,false);
            int i = recordsService.disposeOneVersionRecords(snCode);
            Map<String, String> map1 = new HashMap<>();
            if (i == 1) {
                System.out.println("------------");
                System.out.println("------------");
                System.out.println("------设备没有报件------" + snCode);
                System.out.println("------------");
                map1.put("ret_code", "0");
                map1.put("ret_msge", "该设备没有报件" + snCode);
                return map1;
            }
        }
        if(sy.getActualAddiAmount()==null){
            sy.setActualAddiAmount(sy.getAddi_amount());
        }
        if(StringUtils.isBlank(sy.getActualFeeName())){
            sy.setActualFeeName(sy.getFee_name());
        }
        if(sy.getIsSpecial()==null){
            sy.setIsSpecial(2);
        }
        sy=this.flcl(sy);
        // 交易之前先判断该设备激活没有 没有激活激活
        /*****************  xxl加的   ***************************/
        // 1先判断是否偷单查询代理表查看偷单开关，偷单比例，多少钱往上偷单 不偷单正常往下走  偷单要生成偷单记录表 在自己的交易记录表中添加个字段 表示该条记录被偷单
        BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(snCode);
        if (bizMerchant == null) {
           /* if (sy.getFee_name().contains("+")) {
                // TOU $
                BigDecimal coin = bizMerchTransactionsService.getCoin(sy);
                if (coin.compareTo(new BigDecimal(0)) == 1) {
                    sy.setAddi_amount(Double.valueOf(coin.toString()));
                }
                String[] split = sy.getFee_name().split("\\+");
                sy.setFee_name(split[0]);
            }*/
            String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
            // 存储到我们自己的交易表中
            //int deal = bizMerchTransactionsService.insertPosOneTransactionAmount(sy);
            // 通过uuid查询交易流水id，通过查询出的id，添加交易流水队列
            this.selectAndInsertId(uuid);
            //查询设备表  没有该设备 不能分账  交易还是要存
            BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(sy.getPos_sn());
            if (bizPosMachine == null) {
                Map<String, String> map3 = new HashMap<>();
                map3.put("ret_code", "0");
                map3.put("ret_msg", "设备不存在");
                System.out.println("----------------------");
                System.out.println("-------不存在该设备 交易记录，pos1.0存了记录 不去分账---------------" + sy.getPos_sn());
                System.out.println("----------------------");
                return map3;
            }
            BizMerchantEntry bizMerchantEntry1 = bizMerchantEntryService.getBizMerchantEntryBySn(snCode);
            if (!"3".equals(bizMerchantEntry1.getIsAudit())) { //更新为已审核
                String merchantNo = bizMerchantEntry1.getMerchantNo();
                String proMerSub = "3";
                //更新商户入件状态
                bizMerchantEntryService.updateMerchantEntry(merchantNo, proMerSub);
                //更新激活表状态
                recordsService.updatePosRecordsStatus(snCode);
                //更新设备表
                bizPosMachineService.updatePosPosMachine(snCode);
            }
            // 分账 交易成功
            if (sy.getHost_ret_code().equals("00") || sy.getHost_ret_code().equals("10") || sy.getHost_ret_code().equals("11")) {
                sy.setUuid(uuid);
                if (String.valueOf(sy.getTrans_type()).equals("291")) {
                    //返现
                    bizTransactionAmount.cashMoney(sy);
                }else if (String.valueOf(sy.getTrans_type()).equals("293")) {
                    //流量费
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String amnout=sy.getAmnount().toString();
                    if(amnout.indexOf(".")!=-1){
                        amnout=amnout.substring(0,amnout.indexOf("."));
                    }
                    sy.setSim_amt(Integer.parseInt(amnout));
                    //创建流量费费用收据列表
                    BizFeesCharged bizFeesCharged=bizTransactionAmount.createSimAmt(sy);
                    SynchronizationDataDTO sy1 = new SynchronizationDataDTO();
                    sy1.setSim_amt(Integer.parseInt(amnout));
                    sy1.setPos_sn(sy.getPos_sn());
                    sy1.setHost_date(sdf.format(new Date()));
                    sy1.setUuid(bizFeesCharged.getUuid());
                    sy1.setMerchant_no(sy.getMerchant_no());
                    bizTransactionAmount.returnSimAmt(sy1,false);

                } else {
                    //分账
                    bizTransactionAmount.castAccount(sy);
                    //+3分账
                    Long deptId=bizTransactionAmountMapper.selectDeptIdByPosCode(sy.getPos_sn());
                    if(deptId == 118 || deptId == 117){
                        sharePlusThree(sy);
                    }

                }
                //转发给利盟伙伴
                String hostDate = year + month + day;
                sy.setHost_date(hostDate);
                sy.setOrgncode(posMachineBySnCode.getMerchId().toString());
                sendToLMHB(sy);

                int i = recordsService.disposeOneVersionRecords(snCode);
                //
                Map<String, String> map1 = new HashMap<>();
                if (i == 1) {
                    System.out.println("------------");
                    System.out.println("------------");
                    System.out.println("------设备没有报件------" + snCode);
                    System.out.println("------------");
                    map1.put("ret_code", "0");
                    map1.put("ret_msge", "该设备没有报件" + snCode);
                    return map1;
                }
            } else {
                // 交易失败
                System.out.println("交易失败-----------------" + sy);
            }
            Map<String, String> map1 = new HashMap<>();
            if (uuid !=null) {
                map1.put("ret_code", "0");
                map1.put("ret_msge", "处理成功");
            }
            return map1;
        } else {
            Boolean b = judgeExtract(bizMerchant, sy);
//            Boolean b = true;
            if (b) {  // 偷单
                sy.setWhetherSteal(1);
                String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
                // 存储到我们自己的交易表中
                sy.setUuid(uuid);
//                int deal = bizMerchTransactionsService.insertbizMerchTransactions(sy);
                // 通过uuid查询交易流水id，通过查询出的id，添加交易流水队列
                this.selectAndInsertId(uuid);
                    //更新这个人的钱包 把偷得手续费加到自己钱包
//                bizMerchTransactionsService.updateWallet(String.valueOf(sy.getAddi_amount()), bizMerchant.getUserId());
                Map<String, String> map1 = new HashMap<>();
                if (uuid !=null) {
                    map1.put("ret_code", "0");
                    map1.put("ret_msge", "处理成功");
                }
                return map1;
            } else {
                /*if (sy.getFee_name().contains("+")) {
                    // TOU $
                    BigDecimal coin = bizMerchTransactionsService.getCoin(sy);
                    if (coin.compareTo(new BigDecimal(0)) == 1) {
                        sy.setAddi_amount(Double.valueOf(coin.toString()));
                    }
                    String[] split = sy.getFee_name().split("\\+");
                    sy.setFee_name(split[0]);
                }*/
                String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
                // 存储到我们自己的交易表中
               // int deal = bizMerchTransactionsService.insertPosOneTransactionAmount(sy);
                // 通过uuid查询交易流水id，通过查询出的id，添加交易流水队列
                this.selectAndInsertId(uuid);
                //查询设备表  没有该设备 不能分账  交易还是要存
                BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(sy.getPos_sn());
                if (bizPosMachine == null) {
                    Map<String, String> map3 = new HashMap<>();
                    map3.put("ret_code", "0");
                    map3.put("ret_msg", "设备不存在");
                    System.out.println("----------------------");
                    System.out.println("-------不存在该设备 交易记录，pos1.0存了记录 不去分账---------------" + sy.getPos_sn());
                    System.out.println("----------------------");
                    return map3;
                }
                // 分账 交易成功
                if (sy.getHost_ret_code().equals("00") || sy.getHost_ret_code().equals("10") || sy.getHost_ret_code().equals("11")) {

                    sy.setUuid(uuid);
                    if (String.valueOf(sy.getTrans_type()).equals("291")) {
                        //返现
                        bizTransactionAmount.cashMoney(sy);
                    }else if (String.valueOf(sy.getTrans_type()).equals("293")) {
                        //流量费
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String amnout=sy.getAmnount().toString();
                        if(amnout.indexOf(".")!=-1){
                            amnout=amnout.substring(0,amnout.indexOf("."));
                        }
                        sy.setSim_amt(Integer.parseInt(amnout));
                        //创建流量费费用收据列表
                        BizFeesCharged bizFeesCharged=bizTransactionAmount.createSimAmt(sy);
                        SynchronizationDataDTO sy1 = new SynchronizationDataDTO();
                        sy1.setSim_amt(Integer.parseInt(amnout));
                        sy1.setPos_sn(sy.getPos_sn());
                        sy1.setHost_date(sdf.format(new Date()));
                        sy1.setUuid(bizFeesCharged.getUuid());
                        sy1.setMerchant_no(sy.getMerchant_no());
                        bizTransactionAmount.returnSimAmt(sy1,false);

                    }  else {
                        //分账
                        bizTransactionAmount.castAccount(sy);
                        //+3分账
                        Long deptId=bizTransactionAmountMapper.selectDeptIdByPosCode(sy.getPos_sn());
                        if(deptId == 118 || deptId == 117){
                            sharePlusThree(sy);
                        }
                    }
                    //转发给利盟伙伴
                    String hostDate = year + month + day;
                    sy.setHost_date(hostDate);
                    sy.setOrgncode(posMachineBySnCode.getMerchId().toString());
                    sendToLMHB(sy);

                    /**  **/
                    int i = recordsService.disposeOneVersionRecords(snCode);
                    Map<String, String> map1 = new HashMap<>();
                    if (i == 1) {
                        System.out.println("------------");
                        System.out.println("------------");
                        System.out.println("------设备没有报件------" + snCode);
                        System.out.println("------------");
                        map1.put("ret_code", "0");
                        map1.put("ret_msge", "该设备没有报件" + snCode);
                        return map1;
                    }

                } else {
                    // 交易失败
                    System.out.println("交易失败-----------------" + sy);
                }
                Map<String, String> map1 = new HashMap<>();
                if (uuid !=null) {
                    map1.put("ret_code", "0");
                    map1.put("ret_msge", "处理成功");
                }
                return map1;
            }
        }
        /*******************************************/
    }

    public void fastScanCode(SynchronizationDataDTO sy){
        // 去直属代理上级的+3看设置的多少
        BizPosMachine bizPosMachine = bizPosMachineService.getPosMachineBySnCode(sy.getPos_sn());
        BizMerchant bizMerchantMerch = bizMerchantService.getMerchantByMerchId(bizPosMachine.getMerchId());
        BizAgentOpenAccount bizAgentOpenAccount = bizUserAccountService.getBizAgentOpenAccountByMerchId(bizPosMachine.getMerchId());
        int i=0;
        if(!"0".equals(bizAgentOpenAccount.getPlusThree())){// 直属代理
            BigDecimal scanCodePlusThree = new BigDecimal(bizAgentOpenAccount.getPlusThree()).divide(new BigDecimal(2));
            System.out.println(sy.getOrder_no()+"快捷扫码服务费分润直属代理:"+bizPosMachine.getMerchId()+",给钱是:"+scanCodePlusThree);
            //打钱
            shareMoney(bizPosMachine.getMerchId(),bizMerchantMerch.getUserId(),String.valueOf(scanCodePlusThree),sy,i);
            i++;
        }
        Long parentMerchId = bizMerchantMerch.getParentId();// 上级
        String plusThreeParent = bizAgentOpenAccount.getPlusThree();// 本级服务费
        if("3".equals(plusThreeParent)){
            return;
        }
        while(true){
            // 查上级
            BizMerchant merchantParent = bizMerchantService.getMerchantByMerchId(parentMerchId);
            BizAgentOpenAccount bizAgentOpenAccountParent = bizUserAccountService.getBizAgentOpenAccountByMerchId(merchantParent.getMerchId());
            BigDecimal three = new BigDecimal(bizAgentOpenAccountParent.getPlusThree()).subtract(new BigDecimal(plusThreeParent)).setScale(2,BigDecimal.ROUND_DOWN);
            three = three.divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_DOWN);
            // 当前人未设置服务费分润   或者  分润差是0 都不分润
            if(!"0".equals(three.toString()) && !"0".equals(bizAgentOpenAccountParent.getPlusThree())) {
                shareMoney(merchantParent.getMerchId(), merchantParent.getUserId(), three.toString(), sy, i);
                System.out.println(sy.getOrder_no()+"快捷扫码服务费分润上级代理:"+merchantParent.getMerchId()+",给钱是:"+three.toString());
                i++;
                parentMerchId = merchantParent.getParentId();
                plusThreeParent = bizAgentOpenAccountParent.getPlusThree();
                if("3".equals(bizAgentOpenAccountParent.getPlusThree())){
                    break;
                }
            }else{
                // 这级不给钱就去找上级
                parentMerchId = merchantParent.getParentId();
                plusThreeParent = bizAgentOpenAccountParent.getPlusThree();
            }
            if(merchantParent.getParentId() == 2){// 到服务中心就停止
                break;
            }
        }
    }

    public void sharePlusThree(SynchronizationDataDTO sy){
        if("6".equals(sy.getChannel())){
            System.out.println(sy.getOrder_no()+"扫码交易,单独处理服务费分账");
            try{
                fastScanCode(sy);
            }catch (Exception e){
                System.out.println(sy.getOrder_no()+"扫码交易,单独处理服务费分账出现异常"+e.getMessage());
            }
            return;
        }
        if (sy.getFee_name().contains("+") && sy.getTrans_type() == 281) {
            String[] split = sy.getFee_name().split("\\+");
            String plusThree = split[1];
            if(!"3".equals(plusThree)){// 不是+3  不管了
                System.out.println(sy.getOrder_no()+"单笔不是+3 不管了");
                return;
            }
            // 去直属代理上级的+3看设置的多少
            BizPosMachine bizPosMachine = bizPosMachineService.getPosMachineBySnCode(sy.getPos_sn());
            BizMerchant bizMerchantMerch = bizMerchantService.getMerchantByMerchId(bizPosMachine.getMerchId());
            BizAgentOpenAccount bizAgentOpenAccount = bizUserAccountService.getBizAgentOpenAccountByMerchId(bizPosMachine.getMerchId());
            int i=0;
            if(!"0".equals(bizAgentOpenAccount.getPlusThree())){// 直属代理
                System.out.println(sy.getOrder_no()+"服务费分润直属代理:"+bizPosMachine.getMerchId()+",给钱是:"+bizAgentOpenAccount.getPlusThree());
                //打钱
                shareMoney(bizPosMachine.getMerchId(),bizMerchantMerch.getUserId(),bizAgentOpenAccount.getPlusThree(),sy,i);
                i++;
            }
            Long parentMerchId = bizMerchantMerch.getParentId();// 上级
            String plusThreeParent = bizAgentOpenAccount.getPlusThree();// 本级服务费
            if("3".equals(plusThreeParent)){
                return;
            }
            while(true){
                // 查上级
                BizMerchant merchantParent = bizMerchantService.getMerchantByMerchId(parentMerchId);
                BizAgentOpenAccount bizAgentOpenAccountParent = bizUserAccountService.getBizAgentOpenAccountByMerchId(merchantParent.getMerchId());
                BigDecimal three = new BigDecimal(bizAgentOpenAccountParent.getPlusThree()).subtract(new BigDecimal(plusThreeParent));
                // 当前人未设置服务费分润   或者  分润差是0 都不分润
                if(!"0".equals(three.toString()) && !"0".equals(bizAgentOpenAccountParent.getPlusThree())) {
                    shareMoney(merchantParent.getMerchId(), merchantParent.getUserId(), three.toString(), sy, i);
                    System.out.println(sy.getOrder_no()+"服务费分润上级代理:"+merchantParent.getMerchId()+",给钱是:"+three.toString());
                    i++;
                    parentMerchId = merchantParent.getParentId();
                    plusThreeParent = bizAgentOpenAccountParent.getPlusThree();
                    if("3".equals(bizAgentOpenAccountParent.getPlusThree())){
                        break;
                    }
                }else{
                    // 这级不给钱就去找上级
                    parentMerchId = merchantParent.getParentId();
                    plusThreeParent = bizAgentOpenAccountParent.getPlusThree();
                }
                if(merchantParent.getParentId() == 2){// 到服务中心就停止
                    break;
                }
            }
//            List<BizMerchant> listMerchant = bizMerchantMapper.getParentsByMerchId(bizPosMachine.getMerchId());
//            for(BizMerchant bizMerchant : listMerchant){
//                if(!"0".equals(bizMerchant.getPlusThree())){
//                    System.out.println(sy.getOrder_no()+"上级代理:"+bizMerchant.getMerchId()+",给钱是"+bizMerchant.getPlusThree());
//                    //打钱
//                    shareMoney(bizMerchant.getMerchId(),bizMerchant.getUserId(),bizMerchant.getPlusThree(),sy,i);
//                    i++;
//                }
//            }
        }
    }

    public void shareMoney(Long merchId, Long userId,String money,SynchronizationDataDTO sy,int i){
        // 钱包
        BizWallet bizWallet = bizWalletService.getMyWalletByUserId(userId);
        String key = bizWallet.getSecretKey();// 获得密钥
        String amount = bizWallet.getWalletAmount();// 获得钱包余额
        String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
        // 解密
        String walletAmountStr = DESHelperUtil.decrypt(key, amount);
        String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
        // 转换类型
        BigDecimal bigProfit = new BigDecimal(profitAmountStr);
        BigDecimal bigWallet = new BigDecimal(walletAmountStr);
        // 加密
        BigDecimal bigWalletAmount = bigWallet.add(new BigDecimal(money));
        BigDecimal bigProfitAmount = bigProfit.add(new BigDecimal(money));
        String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
        String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
        bizWallet.setWalletAmount(walletMoney);
        bizWallet.setProfitAmount(profitMoney);
        bizWallet.setSecretKey(key);
        bizWalletService.saveOrUpdate(bizWallet);// 把钱存入表中
        // 生成账单
        BizMerchBill merchBill = new BizMerchBill();
        BizMerchant merchant = bizMerchantService.getMerchantByMerchId(merchId);
        merchBill.setMerchId(merchant.getMerchId());// 商户id
        merchBill.setMerchName(merchant.getMerchName());// 商户名称
        merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
        merchBill.setAmount(new BigDecimal(money));// 分润所分的钱
        merchBill.setVar4(sy.getUuid());
        merchBill.setBillDate(sy.getHost_date());
        //分账为0的不存账单表
        if (!merchBill.getAmount().equals(BigDecimal.ZERO)) {
            merchBillService.save(merchBill); // 存账单数据
        }
        //更新分润明细
        ProfitDeatailDTO profitDeatailDTO =  bizSubAccountService.getProfitDeatailDTOByUuid(sy.getUuid(),merchant.getMerchId());
        if(profitDeatailDTO == null){
            System.out.println(sy.getUuid()+"未查询到分润明细");
        }else{
            profitDeatailDTO.setPlusMoney(money);
            bizSubAccountService.updatePlusMoneyProfitDetail(profitDeatailDTO);
        }

    }



    @ApiOperation("补充分润")
    @PostMapping("/bcfr")
    public AjaxResult regestFr(){
        List<BizTransactionAmountEntity> btae=bizTransactionAmount.selectAllAmount();
        int i=0;
        for (BizTransactionAmountEntity b:btae){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SynchronizationDataDTO sy=new SynchronizationDataDTO();
            sy.setPos_sn(b.getPosSn());
            sy.setAmnount(b.getAmnount());
            sy.setAddi_amount(b.getAddiAmount());
            sy.setFee_name(b.getFeeName());
            sy.setUuid(b.getUuid());
            sy.setHost_time(b.getHostTime());
            sy.setMerchant_no(b.getMerchantNo());
            sy.setTerminal_no(b.getTerminalNo());
            sy.setPan(b.getPan());
            sy.setCard_type(b.getCardType());
            sy.setTrans_type(b.getTransType());
            sy.setEnter_mode(b.getEnterMode());
            sy.setPos_trace(b.getPosTrace());
            sy.setChl_date(b.getChlDate());
            sy.setChl_time(b.getChlTime());
            sy.setChl_merchant_no(b.getChlMerchantNo());
            sy.setChl_terminal_no(b.getChlTerminalNo());
            sy.setRetrirefnum(b.getRetrirefnum());
            sy.setAuth_code(b.getAuthCode());
            sy.setHost_ret_code(b.getHostRetCode());
            sy.setBank_code(b.getBankCode());
            sy.setAcq_certificate(b.getAcqCertificate());
            sy.setAcq_name(b.getAcqName());
            sy.setAcq_account_no(b.getAcqAccountNo());
            sy.setOrder_no(b.getOrderNo());
            sy.setMerchId(b.getMerchId());

            sy.setHost_date(sdf.format(b.getHostDate()));
            if(bizTransactionAmount.castAccount(sy).equals("off")){
                System.out.println(sy.getPos_sn());
            }else{
                i++;
            }
        }
        System.out.println(i);
        return AjaxResult.success("处理成功");
    }
    /**
     * 退还订单
     *
     * @param bizMerchTransactions
     * @return
     */
    @PostMapping("/refundOrder")
    @ApiOperation("退还订单")
    @Transactional
    public AjaxResult refundOrder(@RequestBody BizMerchTransactions bizMerchTransactions) throws ParseException {
        AjaxResult ajaxResult = AjaxResult.success("退还订单");
        if (bizMerchTransactions.getUuid() == null || "".equals(bizMerchTransactions.getUuid())) {
            return AjaxResult.error("退还失败");
        }
        //更改俩个记录表里的是否偷单状态  并进行分账
        //更改pos1.0通知表
        int row = bizTransactionAmount.updateBizTransactionAmount(bizMerchTransactions);
        String suffix = bizTransactionAmount.selectSuffix(bizMerchTransactions);
        String tableName = "biz_transaction_amount";
        if(StringUtils.isNotBlank(suffix)){
            tableName+="_"+suffix;
        }
        bizMerchTransactions.setTableName(tableName);
        //更改pos1.0通知表(机构表)
        bizTransactionAmount.updateBizTransactionAmountSuffix(bizMerchTransactions);
        //更改交易通知表
//        int row1 = bizTransactionAmount.updateBizMerchTransactions(bizMerchTransactions);
        if (row > 0 ) {//分账
            SynchronizationDataDTO sy = new SynchronizationDataDTO();
            //  用uuid查询pos1.0记录
            BizPosMessage syDTO = bizTransactionAmount.selectPos(bizMerchTransactions);

            //要把查询出来的手续费变成正常的手续费去分账
            //先判断费率有没有“ + ”号  有加号算出新手续费更新手续费 没有则不用更新
            String aaa = syDTO.getFeeName(); //正常的费率
            //查询代理的 merchid userid
//            BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(syDTO.getPosSn());
            //如果是吕志国 就不减钱包钱了  不是就减
//            if (aaa.contains("+")) {
//                int i = aaa.indexOf("+");
//                BigDecimal biaoshouxufei = new BigDecimal(syDTO.getAddiAmount()); // 表里的手续费
//                String coin = aaa.substring(i + 1, aaa.length()).replace(" ", ""); //截取多收的钱
//                syDTO.setCoin(coin);
//                BigDecimal subtract = biaoshouxufei.subtract(new BigDecimal(coin)).setScale(2, BigDecimal.ROUND_HALF_UP);  //正常分账的手续费
//                bizMerchTransactionsService.subtractionWallet(subtract.toString(), bizMerchant.getUserId());
//            } else {
//                bizMerchTransactionsService.subtractionWallet(syDTO.getAddiAmount(), bizMerchant.getUserId());
//            }

            if (aaa.contains("+")) { //表示包含+号  要更新
                int i = aaa.indexOf("+");
                BigDecimal biaoshouxufei = new BigDecimal(syDTO.getAddiAmount()); // 表里的手续费
                String coin = aaa.substring(i + 1, aaa.length()).replace(" ", ""); //截取多收的钱
                syDTO.setCoin(coin);
                BigDecimal subtract = biaoshouxufei.subtract(new BigDecimal(coin)).setScale(2, BigDecimal.ROUND_HALF_UP);  //正常分账的手续费
                //更新数据库的手续费
                syDTO.setAddiAmount(String.valueOf(subtract));
                int row3 = bizTransactionAmount.updateBizTransactionAmountAddiAmount(syDTO);
                //插入拿账分账记录表
                int row4 = bizTransactionAmount.insertBizRateMoney(syDTO);
                sy.setAddi_amount(Double.valueOf(String.valueOf(subtract))); // 新的手续费 去分账
                sy.setFee_name(aaa.substring(0, i).replace(" ", "")); //新费率
            } else {
                sy.setAddi_amount(Double.valueOf(syDTO.getAddiAmount()));
                sy.setFee_name(syDTO.getFeeName());
            }
            String snCode = syDTO.getPosSn();
            String uuid = syDTO.getUuid();
            sy.setPos_sn(syDTO.getPosSn());
            sy.setAmnount(Double.valueOf(syDTO.getAmnount()));
            sy.setUuid(syDTO.getUuid());
            sy.setHost_ret_code(syDTO.getHostRetCode());
            // 分账 交易成功
            if (sy.getHost_ret_code().equals("00") || sy.getHost_ret_code().equals("10") || sy.getHost_ret_code().equals("11")) {
                sy.setUuid(uuid);
                sy.setHost_date(syDTO.getHostDate());
                String result = bizTransactionAmount.castAccount(sy);
                recordsService.disposeOneVersionRecords(snCode);
            } else {
                // 交易失败
                System.out.println("交易失败-----------------" + sy);
            }
            return ajaxResult;
        } else {
            System.out.println("退还订单失败");
            return AjaxResult.error("退还失败");
        }
    }

    /**
     * 退还追溯订单
     *
     * @param bizMerchTransactions
     * @return
     */
    @PostMapping("/ascendRefundOrder")
    @ApiOperation("退还追溯订单")
    @Transactional
    public AjaxResult ascendRefundOrder(@RequestBody BizMerchTransactions bizMerchTransactions) {
        AjaxResult ajaxResult = AjaxResult.success("退还追溯订单");
        String uuid = bizMerchTransactions.getUuid();
        if (bizMerchTransactions.getUuid() == null || "".equals(bizMerchTransactions.getUuid())) {
            return AjaxResult.error("退还失败");
        }
        SynchronizationDataDTO sy = new SynchronizationDataDTO();
        //  用uuid查询pos1.0记录
        BizPosMessage syDTO = bizTrackRecordService.selectOneBizTrack(bizMerchTransactions.getUuid());
        if (syDTO == null) {
            return AjaxResult.error("不存在该条记录");
        }
        //查询账单 都谁分钱
        List<BizProfitDeatail> list = bizMerchTransactionsService.selectBizProfitDeatail(uuid);
        if (list.size() == 0) {
            return AjaxResult.error("没有分润明细");
        }
        //分钱
        bizWalletService.independentAccount(list);
        // String result2 = bizTransactionAmount.castAccountTrack(sy);
        //删除追溯记录
        boolean b = bizTrackRecordService.removeById(syDTO.getId());
        if (b) {
            return AjaxResult.success("成功");
        } else {
            return AjaxResult.error("失败");
        }

    }

    ////判断是否偷单
    public final Boolean judgeExtract(BizMerchant bizMerchant, SynchronizationDataDTO sy) {
        if (bizMerchant.getSwitchSteal().equals("1")&&!"1".equals(sy.getSilenceType())) { // 开关打开
            //判断交易金额是否够偷的最小金额
            String bizAmount = bizMerchant.getMinAmount();
            if (new BigDecimal(sy.getAmnount()).compareTo(new BigDecimal(bizAmount)) > -1) { //大于等于设定的最小偷单金额
                //条件满足 看这单是否偷单
                Boolean b = cyclicUtilization(sy, bizMerchant);
                return b;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /// 判断这单是否偷单
    private final Boolean cyclicUtilization(SynchronizationDataDTO sy, BizMerchant bizMerchant) {
        Random random = new Random();
        int suijishu = random.nextInt(100) + 1;
        //查询偷单比例
        String ratioSteal = bizMerchant.getRatioSteal();
        if (Integer.parseInt(ratioSteal) >= suijishu) {
            return true;
        } else {
            return false;
        }
    }


    public String doPost(String url,String data){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //创建请求内容
            String jsonStr = data;
            StringEntity entity = new StringEntity(jsonStr,"utf-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * @author: haoran
     * @date: 2022/8/1
     * 方法名称： 通过uuid查询交易流水id
     *           通过查询出的id，添加交易流水队列
     */
//    @Transactional
    public void selectAndInsertId(String uuid) {
        // 通过uuid查询交易通知表id
        Long transactionAmountId = bizMerchTransactionsService.selectAndInsertId(uuid);
        BizTransactionEntity bizTransactionEntity = new BizTransactionEntity();
        bizTransactionEntity.setTransactionAmountId(transactionAmountId);
        bizTransactionEntity.setCreateTime(DateUtils.getNowDate());
        // 新增交易流水通知表信息
        bizMerchTransactionsService.insert(bizTransactionEntity);
        try {
            transactionService.statistic(transactionAmountId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/bizWallet")
    @Transactional
    public AjaxResult ascendRefundOrder() {
        return AjaxResult.success(bizWalletService.getMyWalletIsNull());
    }

    @PostMapping("/synchronousFenRun")
    @Transactional
    public AjaxResult synchronousFenRun() {
        List<BizPosMessage> syDTO = bizTransactionAmount.selectPosSy();
        for (BizPosMessage bizPosMessage: syDTO){
            SynchronizationDataDTO sy = new SynchronizationDataDTO();
            BizMerchTransactions bizMerchTransactions =new BizMerchTransactions();
            bizMerchTransactions.setUuid(bizPosMessage.getUuid());
            sy.setAddi_amount(Double.valueOf(bizPosMessage.getAddiAmount()));
            sy.setFee_name(bizPosMessage.getFeeName());
            String snCode = bizPosMessage.getPosSn();
            String uuid = bizPosMessage.getUuid();
            sy.setPos_sn(bizPosMessage.getPosSn());
            sy.setAmnount(Double.valueOf(bizPosMessage.getAmnount()));
            sy.setUuid(bizPosMessage.getUuid());
            sy.setHost_ret_code(bizPosMessage.getHostRetCode());
            sy.setTrans_type(Integer.parseInt(bizPosMessage.getTransType()));
            // 分账 交易成功
            if (sy.getHost_ret_code().equals("00") || sy.getHost_ret_code().equals("10") || sy.getHost_ret_code().equals("11")) {
                sy.setUuid(uuid);
                sy.setHost_date(bizPosMessage.getHostDate());
                if (String.valueOf(sy.getTrans_type()).equals("291")) {
                    //返现
                    bizTransactionAmount.cashMoney(sy);
                } else {
                    //分账
                    bizTransactionAmount.castAccount(sy);
                }
            } else {
                // 交易失败
                System.out.println("交易失败-----------------" + sy);
            }
        }
        return AjaxResult.success();
    }
    // 转发
    private void  sendToLMHB(SynchronizationDataDTO sy) {
        List<BizOrganization> list = bizMerchantService.selectBizOrganization("OUTMER");
        if (list.size() > 0) {
            for (BizOrganization bizOrganizations : list) {
                if (bizOrganizations.getOrgncode().equals(sy.getOrgncode())) {
                    String orgip = bizOrganizations.getOrgip();
                    String orgport = bizOrganizations.getOrgport();
                    String url = orgip + orgport;
                    Map<String, String> data = new HashMap<String, String>();
                    data.put("host_date", sy.getHost_date());
                    data.put("host_time", sy.getHost_time());
                    data.put("merchant_no", sy.getMerchant_no());
                    data.put("terminal_no", sy.getTerminal_no());
                    data.put("pan", sy.getPan());
                    data.put("amnount", sy.getAmnount().toString());
                    data.put("addi_amount", sy.getAddi_amount().toString());
                    data.put("fee_name", sy.getFee_name());
                    data.put("card_type",String.valueOf(sy.getCard_type()) );
                    data.put("trans_type", String.valueOf(sy.getTrans_type()));
                    data.put("enter_mode", sy.getEnter_mode());
                    data.put("pos_sn", sy.getPos_sn());
                    data.put("pos_trace", sy.getPos_trace());
                    data.put("chl_date", sy.getChl_date());
                    data.put("chl_time", sy.getChl_time());
                    data.put("chl_merchant_no", sy.getChl_merchant_no());
                    data.put("chl_terminal_no", sy.getChl_terminal_no());
                    data.put("chl_merchant_name", sy.getChl_merchant_name());
                    data.put("retrirefnum", sy.getRetrirefnum());
                    data.put("auth_code", sy.getAuth_code());
                    data.put("host_ret_code", sy.getHost_ret_code());
                    data.put("acq_ret_code", sy.getAcq_ret_code());
                    data.put("bank_code", sy.getBank_code());
                    data.put("acq_certificate", sy.getAcq_certificate());
                    data.put("acq_name", sy.getAcq_name());
                    data.put("acq_account_no", sy.getAcq_account_no());
                    data.put("scan_merchant_no", sy.getScan_merchant_no());
                    data.put("scan_mch_id", sy.getScan_mch_id());
                    data.put("order_no", sy.getOrder_no());
                    data.put("platform_no", sy.getPlatform_no());
                    data.put("orgncode", sy.getOrgncode());
                    data.put("orgnname", sy.getOrgnname());
                    data.put("tran_sim",String.valueOf(sy.getTran_sim()) );
                    data.put("sim_amt", String.valueOf(sy.getSim_amt()));
                    String result = doPost(url, new Gson().toJson(data));
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String ret_code = jsonObject.getString("ret_code");
                    if (ret_code.equals("0")){
                        System.out.println("--------------");
                        System.out.println("转发到---->" + bizOrganizations.getOrgnname());
                        System.out.println("--------------");
                    }
                }
            }
        }

    }
    public List<SynchronizationDataDTO> changeTrading(JSONObject jsonObject){
        String hrtMid=jsonObject.getString("hrtMid");//商户编号
        String sn=jsonObject.getString("sn");//设备SN
        String txnSamt=jsonObject.getString("txnSamt");//交易金额
        String txnFee=jsonObject.getString("txnFee");//手续费
        String txnday=jsonObject.getString("txnday");//交易日期
        String txntime=jsonObject.getString("txntime");//交易时间
        String txnCard=jsonObject.getString("txnCard");//交易卡号（脱敏）/扫码交易为空
        String txnType=jsonObject.getString("txnType");//交易类型
        String isFirst=jsonObject.getString("isFirst");//是否首笔
        String orderid=jsonObject.getString("orderid");//订单号
        String servicefee=jsonObject.getString("servicefee");//押金
        String cashfee=jsonObject.getString("cashfee");//提现费
        String gprsmoney=jsonObject.getString("gprsmoney");//流量费
        SynchronizationDataDTO sy=new SynchronizationDataDTO();
        sy.setMerchant_no(hrtMid);
        sy.setPos_sn(sn);
        sy.setAmnount(Double.valueOf(txnSamt));
        sy.setAddi_amount(Double.valueOf(txnFee));
        sy.setHost_date(txnday);
        sy.setHost_time(txntime);
        sy.setPan(txnCard);
        sy.setCard_type(txnType.equals("刷卡")?2:8);
        sy.setOrder_no(orderid);
        sy.setHost_ret_code("00");
        sy.setTrans_type(281);
        List<SynchronizationDataDTO> syList=new ArrayList<SynchronizationDataDTO>();
        //计算费率
        //计算费率
        String feeName="";
        BigDecimal ruleFee=new BigDecimal(txnFee);
        if(StringUtils.isNotBlank(cashfee)){
            feeName="+"+cashfee;
        }
        BigDecimal feeNameBig=ruleFee.divide(new BigDecimal(txnSamt),10, RoundingMode.DOWN).multiply(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_DOWN);
        feeName="实时"+feeNameBig.toString()+feeName;
        sy.setFee_name(feeName);
        System.out.println(feeName);
        //判定是否是押金交易
        if(StringUtils.isNotBlank(servicefee)){
            SynchronizationDataDTO syServiceFee=new SynchronizationDataDTO();
            syServiceFee.setMerchant_no(hrtMid);
            syServiceFee.setPos_sn(sn);
            syServiceFee.setAmnount(Double.valueOf(servicefee));
            syServiceFee.setAddi_amount(0.00);
            syServiceFee.setFee_name(feeName);
            syServiceFee.setHost_date(txnday);
            syServiceFee.setHost_time(txntime);
            syServiceFee.setPan(txnCard);
            syServiceFee.setCard_type(txnType.equals("刷卡")?2:8);
            syServiceFee.setOrder_no(orderid);
            syServiceFee.setHost_ret_code("00");
            syServiceFee.setTrans_type(291);
            syList.add(syServiceFee);
        }
        //判定是否是流量费交易
        if(StringUtils.isNotBlank(gprsmoney)){
            SynchronizationDataDTO syGprsmoney=new SynchronizationDataDTO();
            syGprsmoney.setMerchant_no(hrtMid);
            syGprsmoney.setPos_sn(sn);
            syGprsmoney.setAmnount(Double.valueOf(gprsmoney));
            syGprsmoney.setAddi_amount(0.00);
            syGprsmoney.setFee_name(feeName);
            syGprsmoney.setHost_date(txnday);
            syGprsmoney.setHost_time(txntime);
            syGprsmoney.setPan(txnCard);
            syGprsmoney.setCard_type(txnType.equals("刷卡")?2:8);
            syGprsmoney.setOrder_no(orderid);
            syGprsmoney.setHost_ret_code("00");
            syGprsmoney.setTrans_type(293);
            syList.add(syGprsmoney);
        }
        syList.add(sy);
        return syList;
    }

    public SynchronizationDataDTO flcl(SynchronizationDataDTO sy){
        String feeName=sy.getFee_name();
        //实时费率按60下发分润
        if("实时费率".equals(feeName)){
            //重新计算费率
            Double amnount=sy.getAmnount();
            BigDecimal amnountDec=new BigDecimal(amnount);
            BigDecimal addiAmount = amnountDec.multiply(new BigDecimal("0.006")).setScale(2, BigDecimal.ROUND_DOWN);
            sy.setAddi_amount(Double.parseDouble(addiAmount.toString()));
            sy.setFee_name("实时0.60");
            return  sy;
        }
        //计算附加费
        String subFee="";
        BigDecimal fjf=new BigDecimal("0");
        String [] feeNameArr=feeName.split("\\+");
        if(feeNameArr.length>1){
            fjf=new BigDecimal(feeNameArr[1]);
            subFee="+"+feeNameArr[1];
        }
        //重新计算费率
        Double amnount=sy.getAmnount();
        BigDecimal amnountDec=new BigDecimal(amnount);
        BigDecimal simAmt=new BigDecimal(sy.getAddi_amount());
        simAmt=simAmt.subtract(fjf);
        BigDecimal fee=simAmt.divide(amnountDec,4,BigDecimal.ROUND_DOWN);
        if(fee.compareTo(new BigDecimal("0.0068"))>0) {
            BigDecimal addiAmount = amnountDec.multiply(new BigDecimal("0.0068")).setScale(2, BigDecimal.ROUND_DOWN).add(fjf);
            sy.setAddi_amount(Double.parseDouble(addiAmount.toString()));
            sy.setFee_name("实时0.68"+subFee);
        }

        return sy;
    }


    @GetMapping("/checkWallet")
    public void checkWallet(Long merchId){
        //获取账单余额
        List<BizMerchBill> billList=bizMerchantMapper.getAllYE(merchId);
        //获取钱包余额
        for(BizMerchBill merchBill:billList){
            Wallet wallet=bizMerchantMapper.selectWalletByMerchId(merchBill.getMerchId());
            String key=wallet.getSecretKey();
            String secWalletAmount=wallet.getWalletAmount();
            BigDecimal walletAmout=new BigDecimal(DESHelperUtil.decrypt(key, secWalletAmount));
            //输出账单与钱包差
            System.out.println("代理ID：\t"+merchBill.getMerchId()+"\t代理名称：\t"+merchBill.getMerchName()+"\t账单余额：\t"+merchBill.getAmount()+"\t钱包余额：\t"+walletAmout.toString()+"\t余额差：\t"+merchBill.getAmount().subtract(walletAmout).setScale(2,BigDecimal.ROUND_DOWN));

        }



    }

    @PostMapping("/closure")
    public AjaxResult closureTrans(@RequestBody String data) {
        System.out.println("接受数据"+data);
        JSONObject jsonObject = JSONObject.parseObject(data);
//        String pos_sn=jsonObject.getString("pos_sn");
//        String amnount=jsonObject.getString("amnount");
//        String host_date=jsonObject.getString("host_date");
        Long transactionAmountId = Long.parseLong(jsonObject.getString("id"));
        try {
            // 通过uuid查询交易通知表id
//            Long transactionAmountId = bizMerchTransactionsService.selectAndInsertIdForClosure(pos_sn, amnount, host_date);
            BizTransactionEntity bizTransactionEntity = new BizTransactionEntity();
            bizTransactionEntity.setTransactionAmountId(transactionAmountId);
            bizTransactionEntity.setCreateTime(com.cykj.common.utils.DateUtils.getNowDate());
            // 新增交易流水通知表信息
            bizMerchTransactionsService.insert(bizTransactionEntity);
            transactionService.statistic(transactionAmountId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }


















}
